import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/util/update/update_info_model.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_update_dialog/flutter_update_dialog.dart';
import 'dart:io';

import 'common.dart';

typedef InstallCallback = Function(String filePath);

class UpdatePrompter {
  /// 版本更新信息
  final UpdateInfoModelData updateEntity;

  final InstallCallback onInstall;

  UpdateDialog _dialog;

  double _progress = 0.0;

  File _apkFile;

  UpdatePrompter({@required this.updateEntity, @required this.onInstall});

  void show(BuildContext context) async {
    if (_dialog != null && _dialog.isShowing()) {
      return;
    }
    String title = "是否升级到${Platform.isAndroid?updateEntity.androidVersion:updateEntity.iosVersion}版本？";
    // String updateContent = getUpdateContent();
    if (Platform.isAndroid) {
      _apkFile = await CommonUtils.getApkFileByUpdateEntity(updateEntity);
    }
    if (_apkFile != null && _apkFile.existsSync()) {
      _dialog = UpdateDialog.showUpdate(
        context,
        title: title,
        updateContent: Platform.isAndroid?updateEntity.androidExplain:updateEntity.iosExplain,
        updateButtonText: "安装",
        extraHeight: 10,
        // enableIgnore: updateEntity.isIgnorable,
        isForce: updateEntity.isForce,
        onUpdate: doInstall,
      );
    } else {
      _dialog = UpdateDialog.showUpdate(
        context,
        title: title,
        updateContent: Platform.isAndroid?updateEntity.androidExplain:updateEntity.iosExplain,
        extraHeight: 10,
        // enableIgnore: updateEntity.isIgnorable,
        isForce: updateEntity.isForce,
        onUpdate: onUpdate,
      );
    }
  }

  // String getUpdateContent() {
  //   String targetSize =
  //       CommonUtils.getTargetSize(updateEntity.apkSize.toDouble());
  //   String updateContent = "";
  //   if (targetSize.isNotEmpty) {
  //     updateContent += "新版本大小：$targetSize\n";
  //   }
  //   updateContent += updateEntity.modifyContent;
  //   return updateContent;
  // }

  void onUpdate() {
    if (Platform.isIOS) {
      doInstall();
      return;
    }


    UpLoadFileDao.downloadFile(updateEntity.androidAppUrl, _apkFile.path,
        onReceiveProgress: (int count, int total) {

          _progress = count.toDouble() / total;
      if (_progress <= 1.0001) {
        _dialog.update(_progress);
      }
    }).then((value) {
      doInstall();
    }).catchError((value) {
      toastError("下载失败！");
      _dialog.dismiss();
    });
  }

  /// 安装
  void doInstall() {
    if (Platform.isIOS&&updateEntity.isForce) {
      onInstall.call(_apkFile != null ? _apkFile.path : updateEntity.iosAppUrl);

      return;
    }
    _dialog.dismiss();
    onInstall.call(_apkFile != null ? _apkFile.path : updateEntity.iosAppUrl);
  }
}
